<?php

namespace App\Providers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        \Validator::extend('mobile', function ($attribute, $value, $parameters, $validator) {
            return $validator->validateRegex($attribute, $value, ['/^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/']);
        });
        if (env('SQL_PRINT', false)) {
            DB::listen(
                function ($sql) {
                    foreach ($sql->bindings as $i => $binding) {
                        if ($binding instanceof \DateTime) {
                            $sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
                        } else {
                            if (is_string($binding)) {
                                $sql->bindings[$i] = "'$binding'";
                            }
                        }
                    }

                    $query = str_replace(['%', '?'], ['%%', '%s'], $sql->sql);
                    $query = vsprintf($query, $sql->bindings);
                    $logFile = fopen(
                        storage_path('logs' . DIRECTORY_SEPARATOR . 'query_' . date('Y-m-d') . '.log'),
                        'a+'
                    );
                    fwrite($logFile, '[' . date('Y-m-d H:i:s') . '] ' . $query . ';' . PHP_EOL);
                    fclose($logFile);
                }
            );
        }
    }
}
